package com.pig4cloud.pig.djjk.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * @className: HttpUtil
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2025/6/3
 **/
public class HttpUtil {
    public static String postRequest(String url, String body) {
        StringBuilder result = new StringBuilder();
        URLConnection conn = null;
        try {
            // 先创建URL对象，然后再设置连接参数
            URL realUrl = new URL(url);
            conn = realUrl.openConnection();

            // 设置连接参数
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(20000);
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");

            // 提交数据
            try (OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8")) {
                out.write(body);
                out.flush();
            }

            // 读取返回数据
            try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
                String line;
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();  // 你可以在这里加入更复杂的异常日志记录
        }
        return result.toString();
    }
}
